package com.yk.filedownload.downloader.DownloadCell.impl;

import com.yk.filedownload.ConfigIt.Configuration;
import com.yk.filedownload.downloader.DownloadCell.CommonCell;
import com.yk.filedownload.entity.DataCarrier;
import com.yk.filedownload.util.logger.ExceptionCatcher;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Project Name:cykfiledownload
 * File Name:MuilThreadCell
 * Package Name:com.yk.filedownload.downloader.service.muilThreadDownload.impl
 * Date:2017\12\7 0007
 * Author:dengtianjia
 * Description:
 * Copyright (c) 2017, 重庆云凯科技有限公司 All Rights Reserved.
 */
public class MuilThreadCell  extends CommonCell {

    private Logger logger = Logger.getLogger(MuilThreadCell.class);

    private String URL ;

    private String RANGE ;

    private String uuid;

    private int packNum;

    private Integer RealTimeSize = 0;

    private Double rate = 30.0;

    private long startTime = 0;

    private Integer packSize;

    private ExceptionCatcher catcher = new ExceptionCatcher();

    public MuilThreadCell(String uuid,String url , String RANGE ,int packNum ,Integer packSize){
        this.uuid = uuid;
        this.URL = url;
        this.RANGE = RANGE;
        this.packNum = packNum;
        this.packSize = packSize ;
    }

    @Override
    public void run() {
        try {
            System.out.println("进入多文件下载");
            System.out.println(uuid);
            startTime = System.currentTimeMillis();

            byte[] mateData = null;

            URL url_now = new URL(URL);

            HttpURLConnection conn = (HttpURLConnection) url_now.openConnection();

            conn.setRequestMethod("GET");

            conn.setRequestProperty("Range","bytes="+RANGE);

            int code = conn.getResponseCode();

            if( code == 206 ){

                InputStream in = conn.getInputStream();

                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();

                byte[] buff = new byte[1024];

                int rc = 0;

                while ((rc = in.read(buff, 0, 1024)) > 0) {

                    swapStream.write(buff, 0, rc);

                    RealTimeSize++;
                    /**
                     * 检测平均下载速率代码块
                     */
                    Long costTime_now =  System.currentTimeMillis() - startTime;
                    if((packSize.doubleValue()/1024.0)/(costTime_now.doubleValue()/1000) < Configuration.MIN_DOWNLOAD_RATE_OF_THREAD){
                        super.BackThrLowRateUrl(URL);
                        super.removeDownloadedDataInRedis(uuid.split("@")[0],packNum);
                        return;
                    }
                }
                mateData = swapStream.toByteArray();

                swapStream.close();

                in.close();

                conn.disconnect();

                DataCarrier carrier = new DataCarrier();

                carrier.setFileId(uuid);

                carrier.CompressData(mateData);
                /**
                 * 测试代码块
                 */
                File file = new File("H:/test/file/"+uuid+".temp");
                FileOutputStream outputStream = new FileOutputStream(file);
                outputStream.write(carrier.getCompressData());
                /**
                 * 将文件写入redis中
                 */
//                super.dataWriteIntoRedis(carrier,RealTimeSize);

            }

        }catch (Exception e){
            catcher.catchException(e,logger,this);
        }
    }


    @Override
    public Map getSatus() {
        rate = super.getDownLoadRate(RealTimeSize,startTime);
        Map status = new HashMap();
        status.put("Thread_ID" , uuid);
        status.put("Thread_URL",URL);
        status.put("Thread_Rate",rate);
        status.put("Thread_NUM",packNum);
        return status;
    }
}
